<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class LoginController extends Controller
{
   public function index()
   {
      return view('home.login');
   }

   public function logging(Request $request)
   {
       // session(['code' => check()]);
      
      $data = $request->except('_token');
      $username = $data['username'];
      $list = DB::table('user')->select('username', 'userpwd', 'id')->where('username',$username)->first();
      // dd($data['userpass']);
      if($list){
        // echo "true";
        if( $list->userpwd == MD5($data['userpass'] )){
              session(['uname' => $data['username']]);
              session(['id' => $list->id]);
              return redirect('/home/homePage');
        }else{
          return redirect('/doLogin')->with('msg', '密码错误！');
        }

      }else{
        // echo 111111;
        return redirect('/doLogin')->with('msg', '用户名错误！');
      }
      // dd($list); 
   }

   public function register()
   {
   		
   		return view('home.register');
   }      

   public function doLogin(Request $request)
   {
   		// dd(11);
   		$message = [
   		'username.unique'=>'用户名已经存在了',
   		];
   		$this->validate($request,[
   			'username'=>'unique:user,username',
   			],$message);
        $data = $request->except('_token','repass');
        // dd($data);
        $data['regtime'] = time();
        $id = DB::table('user')->insertGetId($data);
         DB::table('user')->where('id', $id)->update(['userpwd' => md5($request->input('userpwd'))]);
        if($id>0){
            return redirect('/register')->with('msg','注册成功');
        }

   }  

   public function logOut(Request $request)
   {
      $request->session()->forget('uname');
       return redirect('/home/homePage');
   }


}
